package com.iretailer.report.web.analyze;

import com.iretailer.report.analyze.commonUtil.Analyze;
import com.iretailer.report.analyze.commonUtil.ResponeResultType;
import com.iretailer.report.analyze.netty.NettyHttpServer;
import com.iretailer.report.aspect.HttpAspect;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/7/22 0022 16:38
 * @Description:
 */
@RestController
public class FlowAnalyze {
    private static Logger log = LoggerFactory.getLogger(FlowAnalyze.class);


    @RequestMapping("/flow/{path}")
    public void analzeFlow(HttpServletResponse response, HttpServletRequest request, @PathVariable String path) {
        if (request.getMethod().toLowerCase().equals("post")) {
            byte[] body = getBody(request);
            if (body != null) {
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("remoreAddr", HttpAspect.getIpAddr(request));
                Analyze keyType = NettyHttpServer.pathMap.get(String.format("/%s", path));
                ResponeResultType status = keyType.springAnalyze(paramsMap, body);
                response.setStatus(status.getHrs().code());
            } else {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    private byte[] getBody(HttpServletRequest request) {
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            byte[] bytes = new byte[request.getContentLength()];
            inputStream.read(bytes);
            return bytes;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }
}
